package com.ljh.user.listener;

import com.ljh.common.constants.Constants;
import com.ljh.common.utils.JSONUtil;
import com.ljh.common.utils.MailUtil;
import com.ljh.user.dataobject.UserInfo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;

/**
 * @author: Themberfue
 * @date: 2025/4/25 16:44
 * @description:
 */
@Slf4j
@Component
public class UserQueueListener {

    @Autowired
    MailUtil mailUtil;

    @RabbitListener(queues = Constants.USER_QUEUE_NAME)
    public void process(Message message, Channel channel) throws IOException {
        // TODO 1. 获取唯一标识，用于确认消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            // TODO 2. 获得消息体
            String body = new String(message.getBody());
            log.info("成功收到消息：body: {}", body);

            UserInfo userInfo = JSONUtil.parse(body, UserInfo.class);
            if (null == userInfo) {
                throw new Exception("用户信息为空");
            }

            // TODO 3. 发送邮件
            mailUtil.sendSampleMail(userInfo.getEmail(),
                    "Welcome To You!",
                    "Welcome To " + userInfo.getUserName() + " Json us!");

            // TODO 4. 确认消息
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            // TODO 5. 异常处理，拒绝消息，并且重发
            log.error("消息处理失败", e);
            channel.basicNack(deliveryTag, true, true);
        }
    }

//    @RabbitListener(bindings = @QueueBinding(
//            value = @Queue(value = Constants.USER_QUEUE_NAME, durable = "true"),
//            exchange = @Exchange(value = Constants.USER_EXCHANGE_NAME, type = ExchangeTypes.FANOUT)
//    ))
//    public void process2() {}
}
